package cn.buk.api.ctrip.Factory;

import cn.buk.api.ctrip.dto.DomesticFlightData;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by yfdai on 15/6/11.
 */
public class ConvertFlightResponseXml2ObjectFactory  extends BaseFactory {

    public static List<DomesticFlightData> convertFlightSearchResponse(String xml) throws DocumentException {
        Document document = new SAXReader().read(new StringReader(xml));
        return convertFlightSearchResponse(document);
    }

    public static List<DomesticFlightData> convertFlightSearchResponse(Document document) {
        XStream xs = createXStream(true);
        xs.processAnnotations(DomesticFlightData.class);

        List flightDataList = document.selectNodes("//FlightsList/*");
        List<DomesticFlightData> fltList = new ArrayList<DomesticFlightData>();
        for(Iterator it = flightDataList.iterator();it.hasNext();){
            Element fltElement = (Element)it.next();

            String xml =  fltElement.asXML();
            DomesticFlightData fltData  = (DomesticFlightData)xs.fromXML(xml);
            fltList.add(fltData);
        }
        return fltList;
    }
}
